package com.lute.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
	private static final SendMail sender = new SendMail();
	private static Properties properties = new Properties();
	
	static {
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "465");
	}
	
	private SendMail() {}
	
	public static SendMail getInstance() {
		return sender;
	}
	
	public void sendMailTo(String toRecipient, String subject, String body) {
		Session session = Session.getInstance(properties,
				  new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication("lutemailer@gmail.com", "lutelut3");
					}
				  });
		
		InternetAddress[] toAddresses = null;
		
		try {
			 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("lutemailer@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(toRecipient));
			message.setSubject(subject);
			message.setText(body);

			Transport.send(message);

		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	public void sendMassMail(String[] bccRecipients, String subject, String body) {
		Session session = Session.getInstance(properties,
				  new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication("lutemailer@gmail.com", "lutelut3");
					}
				  });
		
		InternetAddress[] bccAddresses = null;
		
		try {
			 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("lutemailer@gmail.com"));
			bccAddresses = new InternetAddress[bccRecipients.length];
            for(int i = 0; i < bccRecipients.length; i++) {
                bccAddresses[i] = new InternetAddress(bccRecipients[i]);
            }
            message.setRecipients(Message.RecipientType.BCC, bccAddresses);
			message.setSubject(subject);
			message.setText(body);

			Transport.send(message);

		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isValidEmailAddress(String email) {
		boolean result = true;
	    try {
	       InternetAddress emailAddr = new InternetAddress(email);
	       emailAddr.validate();
	    } catch (AddressException ex) {
	       result = false;
	    }
	    return result;
	}
}
